<template>
    <!-- 该组件的请求可能有问题 每次添加完以后表格不更新 -->
    <div class="container">
        <header>
            <el-button type="primary" @click="open">添加</el-button>
        </header>
        <div class="tableData">
            <el-table :data="tableData" style="width: 100%" :border="true">
                <el-table-column label="时间段" align="center">
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <span style="margin-left: 10px">{{ scope.row.date }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 添加模态框 -->
        <el-dialog v-model="dialogVisible" title="添加时间段" width="30%">
            <el-form ref="formRef" :model="form" label-width="80px">
                <el-form-item label="开始时间">
                    <el-time-picker v-model="form.startTime" format="HH:mm" value-format="HH:mm"></el-time-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-time-picker v-model="form.endTime" format="HH:mm" value-format="HH:mm"></el-time-picker>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addTimeSpan">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getTimeSet, addTimeSet } from '@/api/order/timeset';
import { ElMessage } from 'element-plus';

interface TimeSpan {
    startTime: string;
    endTime: string;
}

interface TimeSetResponse {
    data: {
        timeSpanList: TimeSpan[];
    }[];
}

interface User {
    date: string;
}

const tableData = ref<User[]>([]);
const dialogVisible = ref(false);
const form = ref({
    startTime: '',
    endTime: ''
});

// 打开模态框
const open = () => {
    dialogVisible.value = true;
};

// 格式化时间
const formatTime = (time: string): string => {
    if (typeof time !== 'string' || !time.includes(':')) {
        return ''; // 如果 time 不是有效的时间字符串，返回空字符串
    }

    const [hours, minutes] = time.split(':').map(part => part.padStart(2, '0'));
    const seconds = '00'; // 固定秒数为 00
    return `${hours}:${minutes}:${seconds}`;
};

// 添加时间段
const addTimeSpan = async () => {
    if (form.value.startTime && form.value.endTime) {
        const formattedStartTime = formatTime(form.value.startTime);
        const formattedEndTime = formatTime(form.value.endTime);

        try {
            // 发送的对象只包含 startTime 和 endTime
            await addTimeSet({
                startTime: formattedStartTime,
                endTime: formattedEndTime
            });
            fetchTableData(); // 重新获取数据以更新表格
            dialogVisible.value = false;
            ElMessage.success('时间段添加成功');
        } catch (error) {
            ElMessage.error('保存时间段失败');
        }
    } else {
        ElMessage.error('请选择开始时间和结束时间');
    }
};


// 编辑操作
const handleEdit = (index: number, row: User) => {
    console.log(index, row);
};

// 删除操作
const handleDelete = (index: number, row: User) => {
    const confirmDelete = confirm(`确定要删除时间段: ${row.date} 吗？`);
    if (confirmDelete) {
        tableData.value.splice(index, 1);
    }
};

const fetchTableData = async () => {
    try {
        const response = await getTimeSet() as TimeSetResponse;
        console.log('Fetched data:', response); // 调试信息
        tableData.value = response.data.flatMap(item =>
            item.timeSpanList.map(timeSpan => ({
                date: `${timeSpan.startTime} - ${timeSpan.endTime}`
            }))
        );
        console.log('Updated tableData:', tableData.value); // 调试信息
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

onMounted(() => {
    fetchTableData();
});
</script>

<style scoped lang="scss">
.container {
    padding: 20px;
    margin-left: 80px;

    .tableData {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
    }

    .el-table {
        width: 80%;
        max-width: 1344px;
        margin: 0;
    }

    :deep(.el-dialog) {
        .el-dialog__header {
            background-color: #1892FF;
            padding: 20px;
            margin: 0; // 移除左边距，使背景色填满整个宽度

            .el-dialog__title {
                color: white;
            }
        }
    }
}
</style>
